from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from django.contrib.auth.views import LoginView, LogoutView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from django.db.models import Avg, Count
from django.db.models.functions import Coalesce
from .models import Student, Teacher, Course, StudentScore, TeacherRating
from .forms import StudentForm, TeacherForm, CourseForm, StudentScoreForm, TeacherRatingForm
from django.contrib.auth import logout

class StudentListView(LoginRequiredMixin, ListView):
    model = Student
    template_name = 'student_management/student_list.html'
    context_object_name = 'students'
    login_url = '/students/login/'

class StudentCreateView(LoginRequiredMixin, CreateView):
    model = Student
    form_class = StudentForm
    template_name = 'student_management/student_form.html'
    success_url = reverse_lazy('student-list')
    login_url = '/students/login/'

class StudentUpdateView(LoginRequiredMixin, UpdateView):
    model = Student
    form_class = StudentForm
    template_name = 'student_management/student_form.html'
    success_url = reverse_lazy('student-list')
    login_url = '/students/login/'

class StudentDeleteView(LoginRequiredMixin, DeleteView):
    model = Student
    template_name = 'student_management/student_confirm_delete.html'
    success_url = reverse_lazy('student-list')
    login_url = '/students/login/'

class StudentLoginView(LoginView):
    template_name = 'student_management/login.html'
    success_url = reverse_lazy('student-list')
    redirect_authenticated_user = True

    def get_success_url(self):
        user = self.request.user
        if hasattr(user, 'teacher'):
            return reverse_lazy('course-list')
        return self.success_url

class TeacherListView(LoginRequiredMixin, ListView):
    model = Teacher
    template_name = 'student_management/teacher_list.html'
    context_object_name = 'teachers'
    login_url = '/students/login/'

class TeacherCreateView(LoginRequiredMixin, CreateView):
    model = Teacher
    form_class = TeacherForm
    template_name = 'student_management/teacher_form.html'
    success_url = reverse_lazy('teacher-list')
    login_url = '/students/login/'

class TeacherUpdateView(LoginRequiredMixin, UpdateView):
    model = Teacher
    form_class = TeacherForm
    template_name = 'student_management/teacher_form.html'
    success_url = reverse_lazy('teacher-list')
    login_url = '/students/login/'

class TeacherDeleteView(LoginRequiredMixin, DeleteView):
    model = Teacher
    template_name = 'student_management/teacher_confirm_delete.html'
    success_url = reverse_lazy('teacher-list')
    login_url = '/students/login/'

class CourseListView(LoginRequiredMixin, ListView):
    model = Course
    template_name = 'student_management/course_list.html'
    context_object_name = 'courses'

class CourseCreateView(LoginRequiredMixin, CreateView):
    model = Course
    form_class = CourseForm
    template_name = 'student_management/course_form.html'
    success_url = reverse_lazy('course-list')

class CourseUpdateView(LoginRequiredMixin, UpdateView):
    model = Course
    form_class = CourseForm
    template_name = 'student_management/course_form.html'
    success_url = reverse_lazy('course-list')

class CourseDeleteView(LoginRequiredMixin, DeleteView):
    model = Course
    template_name = 'student_management/course_confirm_delete.html'
    success_url = reverse_lazy('course-list')

def manage_scores(request, course_id):
    course = get_object_or_404(Course, id=course_id)
    students = Student.objects.all()
    
    if request.method == 'POST':
        for student in students:
            score = request.POST.get(f'score_{student.id}')
            if score:
                StudentScore.objects.update_or_create(
                    student=student,
                    course=course,
                    defaults={'score': score}
                )
        messages.success(request, '成绩已更新')
        return redirect('course-list')
    
    scores = {score.student_id: score.score for score in StudentScore.objects.filter(course=course)}
    context = {
        'course': course,
        'students': students,
        'scores': scores,
    }
    return render(request, 'student_management/manage_scores.html', context)

def rate_teacher(request, course_id):
    course = get_object_or_404(Course, id=course_id)
    
    if request.method == 'POST':
        form = TeacherRatingForm(request.POST)
        if form.is_valid():
            rating = form.save(commit=False)
            if hasattr(request.user, 'student'):
                rating.student = request.user.student
            else:
                student_id = request.POST.get('student')
                if student_id:
                    rating.student = Student.objects.get(id=student_id)
                else:
                    messages.error(request, '请选择学生')
                    return redirect('course-list')
            
            rating.teacher = course.teacher
            rating.course = course
            rating.save()
            messages.success(request, '评分已提交')
            return redirect('course-list')
    else:
        form = TeacherRatingForm()
    
    students = Student.objects.all() if not hasattr(request.user, 'student') else None
    
    context = {
        'form': form,
        'course': course,
        'teacher': course.teacher,
        'students': students,
    }
    return render(request, 'student_management/rate_teacher.html', context)

def teacher_ratings(request, teacher_id):
    teacher = get_object_or_404(Teacher, id=teacher_id)
    ratings = TeacherRating.objects.filter(teacher=teacher)
    avg_rating = ratings.aggregate(Avg('rating'))['rating__avg']
    
    context = {
        'teacher': teacher,
        'ratings': ratings,
        'avg_rating': avg_rating,
    }
    return render(request, 'student_management/teacher_ratings.html', context)

def teacher_ratings_detail(request, teacher_id):
    teacher = get_object_or_404(Teacher, id=teacher_id)
    ratings = TeacherRating.objects.filter(teacher=teacher)\
        .select_related('student', 'course')\
        .order_by('-created_at')
    
    # 计算平均评分
    avg_rating = ratings.aggregate(
        avg_rating=Coalesce(Avg('rating'), 0.0)
    )['avg_rating']
    
    # 按课程分组统计
    course_stats = ratings.values('course__name')\
        .annotate(
            avg_rating=Avg('rating'),
            count=Count('id')
        )
    
    context = {
        'teacher': teacher,
        'ratings': ratings,
        'avg_rating': avg_rating,
        'course_stats': course_stats,
    }
    return render(request, 'student_management/teacher_ratings_detail.html', context)

def logout_view(request):
    logout(request)
    return redirect('login')

class CustomLogoutView(LogoutView):
    next_page = '/students/login/'  # 使用完整的 URL 路径
    
    def get_next_page(self):
        return self.next_page